﻿using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.Text;

namespace IPTV_API.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ChannelController : ControllerBase
    {
        [Route("Channel.m3u8")]
        [HttpGet]
        public IActionResult Get(string? type,string id="zjws") 
        {
            return Redirect(getUrl(id));
        }

        public static string getUrl(string id)
        {
            // 获取id参数
            //string id = "zjws";

            // 频道映射字典
            var n = new Dictionary<string, string>
        {
            {"zjws", "01"},    //浙江卫视
            {"zjqj", "02"},    //浙江钱江
            {"zjjjsh", "03"}, //浙江经济生活
            {"zjjkys", "04"},  //浙江教科影视
            {"zjysyl", "05"},  //浙江影视娱乐
            {"zjmsxx", "06"}, //浙江民生休闲
            {"zjxw", "07"},   //浙江新闻
            {"zjse", "08"},   //浙江少儿
            {"zjlx", "09"},   //浙江留学
            {"zjgj", "10"},    //浙江国际
            {"zjhyg", "11"},  //浙江好易购
            {"zjzjjl", "12"}  //浙江之江纪录
        };

            // 获取频道号，默认01
            string channel = n.TryGetValue(id, out string? value) ? value : "001";

            // 生成路径
            string pathname = $"/channel{channel}/1080p.m3u8";

            // 生成时间戳
            long e = DateTimeOffset.Now.ToUnixTimeSeconds();

            // 生成随机数
            Random rand = new Random();
            string randomStr = rand.Next().ToString();
            string randMd5 = GetMd5Hash(randomStr);

            // 固定密钥
            const string key = "9T08yiAoqM4eeCwV";

            // 生成签名
            string signStr = $"{pathname}-{e}-{randMd5}-0-{key}";
            string r = GetMd5Hash(signStr);

            // 生成认证key
            string auth_key = $"{e}-{randMd5}-0-{r}";

            // 生成最终URL
            string m3u8Url = $"https://zhfivel02.cztv.com/channel{channel}/1080p.m3u8?auth_key={auth_key}";
            return m3u8Url;
        }
        private static string GetMd5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2")); // 保持小写与PHP一致
                }
                return sb.ToString();
            }
        }
    }
}
